﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Mvc;
using YetAnotherChat.ChatCore;
using YetAnotherChat.ChatCore.Interfaces;
using YetAnotherChat.ChatCore.Models;
using YetAnotherChat.ChatUI.Classes;
using YetAnotherChat.EntityFrameworkDataAccess.RepositoryImp;
using YetAnotherChat.MemoryStorage.Imp;
using YetAnotherChat.MemoryStorage.Interfaces;
using YetAnotherChat.TcpServer;
using YetAnotherChat.TcpServer.Interfaces;

namespace YetAnotherChat.ChatUI.ServiceImp
{
    public interface IChatMessageService
    {
        void SaveMessages(ChatMessage[] messages, bool fromWebSocketClient);
        ChatMessage[] GetMessages(Guid userId, Guid topicId, DateTime fromTime);
    }

    /// <summary>
    /// This class manages a IChatMessagePersistenceService to save messages to DB.
    /// It also manage a single WebSocket instance, to push ajax messages to TcpServer
    /// 
    /// </summary>
    public class ChatMessageService : IChatMessageService
    {
        /// <summary>
        /// WebSocketClient, used to connect to TcpServer, pushing msg from ajax call to TcpServer 
        /// </summary>
        private IWebSocketClient SocketClient;

        private IChatMessagePersistenceService _messageSavingService;

        private static ChatMessageService _instance = new ChatMessageService();

        private IChatMessageStore _cacheStore;

        public static IChatMessageService Instance
        {
            get
            {
                return _instance;
            }
        }



        public ChatMessageService()
        {
            //replace this with DI
            _messageSavingService = DependencyResolver.Current.GetService<IChatMessagePersistenceService>();

            _messageSavingService.Started += _messageSavingService_Started;
            _messageSavingService.Stopped += _messageSavingService_Stopped;

            //create interface for WebSocketClient and DI ?
            SocketClient = new WebSocketClient(ConfigurationManager.AppSettings["TcpServerAddress"]) { Origin = ConfigurationManager.AppSettings["TcpServerOrigin"] };

            if (!_messageSavingService.IsRunning)
            {
                _messageSavingService.Start();
            }

            //replace this with DI
            _cacheStore = new ChatMessageStore(new DefaultCache(), new MessageRepository());
        }

        void _messageSavingService_Stopped(object sender, EventArgs e)
        {
            SocketClient.Disconnect();
        }

        void _messageSavingService_Started(object sender, EventArgs e)
        {
            SocketClient.Connect();
        }

        public void SaveMessages(ChatMessage[] messages, bool fromWebSocketClient)
        {
            //add messages to cache!!!
            _cacheStore.AddMessages(messages);


            if (!fromWebSocketClient)
            {
                //just send it, asyncly
                //SocketClient.Send(messages);
                foreach (var m in messages)
                {
                    SocketClient.Send(new { Type = 1, Message = m.Text, FromAjaxWeb = true });
                }
            }

            _messageSavingService.SaveMessages(messages);
        }


        public ChatMessage[] GetMessages(Guid userId, Guid topicId, DateTime fromTime)
        {
            return _cacheStore.GetChatMessage(topicId, userId, fromTime);
        }
    }
}
